import { createStore } from "vuex";

export default createStore({
  state: {
    user: null,
    isLoggedIn: false,
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
    },
    setLoginStatus(state, status) {
      state.isLoggedIn = status;
    },
  },
  actions: {
    login({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        // 模拟登录API调用
        setTimeout(() => {
          if (
            (username === "admin" && password === "admin") ||
            (username === "farmer" && password === "farmer")
          ) {
            const token = "mock-jwt-token";
            localStorage.setItem("token", token);

            // 根据用户名确定角色
            const role = username === "admin" ? "admin" : "farmer";
            const user = {
              id: 1,
              name: username === "admin" ? "张管理员" : "李养殖户",
              role,
            };

            commit("setUser", user);
            commit("setLoginStatus", true);
            resolve(user);
          } else {
            reject(new Error("用户名或密码错误"));
          }
        }, 500);
      });
    },
    logout({ commit }) {
      localStorage.removeItem("token");
      commit("setUser", null);
      commit("setLoginStatus", false);
    },
  },
  getters: {
    isAdmin: (state) => state.user?.role === "admin",
    currentUser: (state) => state.user,
  },
});
